package Q4;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ChatServerRunnable implements Runnable {
    private Socket s;

    public ChatServerRunnable(Socket s) {
        this.s = s;
    }

    // check 判断admin账户
    // 非check 返回源message
    private UserMessage checkAdmin(UserMessage msg) {
        if (null == msg) {
            System.out.println("msg获取失败");
            return new UserMessage("N/A", null);
        }
        if (!"check".equals(msg.getMessageType())) {
            return msg;
        }
        User msgUser = msg.getUser();
        if (msgUser.equals(ChatServer.getAdminUser())) {
            return new UserMessage("success", msgUser);
        } else {
            return new UserMessage("fail", msgUser);
        }

    }

    @Override
    public void run() {
        System.out.println("线程启动");
        ObjectInputStream serverInputStream = null;
        ObjectOutputStream serverOutputStream = null;
        try {
            serverInputStream = new ObjectInputStream(s.getInputStream());
            serverOutputStream = new ObjectOutputStream(s.getOutputStream());
            while (true) {
                Object readObject = serverInputStream.readObject();
                UserMessage message = readObject instanceof UserMessage ? (UserMessage) readObject : null;
                System.out.println("----服务器接收message = " + message);
                message = checkAdmin(message);

                System.out.println("----服务器发送message = " + message);
                serverOutputStream.writeObject(message);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverInputStream != null) {
                    serverInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverOutputStream != null) {
                    serverOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
